package com.tarena.lbs.stock.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.pojo.stock.param.CouponStockParam;
import com.tarena.lbs.pojo.stock.po.CouponStockPO;
import com.tarena.lbs.stock.web.dao.repository.StockRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class StockService {
    @Autowired
    private StockRepository stockRepository;

    public Boolean initCouponStock(CouponStockParam param) {
        //新增 初始化库存成功 没有异常 连接超时 链接拒绝  affected 1row
        //1.封装一个couponStockPO 补充仓鼠 createAt updateAt
        CouponStockPO po=new CouponStockPO();
        BeanUtils.copyProperties(param,po);//couponId,businessId,num
        Date now=new Date();
        po.setCreateAt(now);
        po.setUpdateAt(now);
        //2.调用仓储层写 判断返回值 1 0
        boolean save = stockRepository.save(po);
        return save;
    }

    public Integer getCouponNum(Integer couponId) {
        //select * from coupon_stock where coupon_id=#{}
        QueryWrapper<CouponStockPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("coupon_id",couponId);
        CouponStockPO couponStockPO = stockRepository.getOne(queryWrapper);
        return couponStockPO.getNum();
    }

    public Boolean reduceStock(Integer couponId, Integer num) {
        //update coupon_stock set num=num-#{num} where coupon_id=#{}
        int row=stockRepository.reduceStock(couponId,num);
        return row>0;
    }
}
